//
//  ClockView.m
//  UniversalTableView
//
//  Created by 冷悦 on 16/3/14.
//  Copyright © 2016年 冷悦. All rights reserved.
//

#import "ClockView.h"
@interface ClockView()

@property (nonatomic, strong) CAShapeLayer *circle;

@property (nonatomic, strong) CAShapeLayer *line;

@end

@implementation ClockView

#pragma mark - Private
/**
 *  计算以一点为圆心，给定角度与半径，在圆上的位置
 *
 *  @param center 圆心
 *  @param angle  给定的角度，使用0-360，而不是3.1415926方式
 *  @param radius 半径
 *
 *  @return 圆上的点
 */
- (CGPoint) calcCircleCoordinateWithCenter:(CGPoint)center
                                 withAngle:(CGFloat)angle
                                 andRadius:(CGFloat)radius{
    CGFloat x = radius * cosf(angle * M_PI / 180);
    CGFloat y = radius * sinf(angle * M_PI / 180);
    
    return CGPointMake(center.x + x, center.y + y);
}

- (void)updateShapesCenterPoint:(CGPoint)centerPoint andRadius:(CGFloat)radius{
    CGPoint point1 = [self calcCircleCoordinateWithCenter:centerPoint
                                                withAngle:300
                                                andRadius:radius * 4 / 5];
    CGPoint point2 = [self calcCircleCoordinateWithCenter:centerPoint
                                                withAngle:10
                                                andRadius:radius * 2/ 3];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:point1];
    [path addLineToPoint:centerPoint];
    [path addLineToPoint:point2];
    self.line.path = path.CGPath;
    
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:centerPoint
                                                              radius:radius
                                                          startAngle:0 endAngle:M_PI * 2
                                                           clockwise:YES];
    self.circle.path = circlePath.CGPath;
}

- (void)drawRect:(CGRect)rect {
    CGFloat width = CGRectGetWidth(rect);
    CGFloat height = CGRectGetHeight(rect);
    CGFloat radius = MIN(width, height) / 2.0;
    CGPoint centerPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
    [self updateShapesCenterPoint:centerPoint andRadius:radius];
}

#pragma mark - Setters
- (void)setLineColor:(UIColor *)lineColor{
    self.circle.strokeColor = lineColor.CGColor;
    self.line.strokeColor = lineColor.CGColor;
}

#pragma mark - Getters
- (CAShapeLayer *)circle{
    if (_circle == nil) {
        _circle = [CAShapeLayer new];
        _circle.fillColor = [UIColor clearColor].CGColor;
        [self.layer addSublayer:_circle];
    }
    
    return _circle;
}

- (CAShapeLayer *)line{
    if (_line == nil) {
        _line = [CAShapeLayer new];
        _line.fillColor = [UIColor clearColor].CGColor;
        [self.layer addSublayer:_line];
    }
    
    return _line;
}


@end
